import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/register/index.vue'),
    meta: { title: '注册', hidden: true }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('../views/error/403.vue'),
    meta: { title: '403', hidden: true }
  },
  {
    path: '/',
    component: () => import('../layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'HomeFilled' }
      }
    ]
  },
  // 商品管理
  {
    path: '/product',
    component: () => import('../layout/index.vue'),
    redirect: '/product/list',
    meta: { title: '商品管理', icon: 'Goods', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] },
    children: [
      {
        path: 'list',
        name: 'ProductList',
        component: () => import('../views/product/list.vue'),
        meta: { title: '商品列表', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] }
      },
      {
        path: 'category',
        name: 'ProductCategory',
        component: () => import('../views/product/category.vue'),
        meta: { title: '商品分类', roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'add',
        name: 'ProductAdd',
        component: () => import('../views/product/add.vue'),
        meta: { title: '添加商品', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] }
      },
      {
        path: 'edit/:id',
        name: 'ProductEdit',
        component: () => import('../views/product/edit.vue'),
        meta: { title: '编辑商品', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'], activeMenu: '/product/list' },
        hidden: true
      }
    ]
  },
  // 订单管理
  {
    path: '/order',
    component: () => import('../layout/index.vue'),
    redirect: '/order/list',
    meta: { title: '订单管理', icon: 'List', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT', 'ROLE_MERCHANT_SERVICE'] },
    children: [
      {
        path: 'list',
        name: 'OrderList',
        component: () => import('../views/order/list.vue'),
        meta: { title: '订单列表', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT', 'ROLE_MERCHANT_SERVICE'] }
      },
      {
        path: 'detail/:id',
        name: 'OrderDetail',
        component: () => import('../views/order/detail.vue'),
        meta: { title: '订单详情', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT', 'ROLE_MERCHANT_SERVICE'], activeMenu: '/order/list' },
        hidden: true
      }
    ]
  },
  // 商家管理
  {
    path: '/merchant',
    component: () => import('../layout/index.vue'),
    redirect: '/merchant/list',
    meta: { title: '商家管理', icon: 'Shop', roles: ['ROLE_ADMIN'] },
    children: [
      {
        path: 'list',
        name: 'MerchantList',
        component: () => import('../views/merchant/list.vue'),
        meta: { title: '商家列表', roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'add',
        name: 'MerchantAdd',
        component: () => import('../views/merchant/add.vue'),
        meta: { title: '添加商家', roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'edit/:id',
        name: 'MerchantEdit',
        component: () => import('../views/merchant/edit.vue'),
        meta: { title: '编辑商家', roles: ['ROLE_ADMIN'], activeMenu: '/merchant/list' },
        hidden: true
      }
    ]
  },
  // 营销活动
  {
    path: '/activity',
    component: () => import('../layout/index.vue'),
    redirect: '/activity/promotion',
    meta: { title: '营销活动', icon: 'Present', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] },
    children: [
      {
        path: 'promotion',
        name: 'Promotion',
        component: () => import('../views/activity/promotion.vue'),
        meta: { title: '促销活动', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] }
      },
      {
        path: 'groupon',
        name: 'Groupon',
        component: () => import('../views/activity/groupon.vue'),
        meta: { title: '拼团活动', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] }
      },
      {
        path: 'seckill',
        name: 'Seckill',
        component: () => import('../views/activity/seckill.vue'),
        meta: { title: '秒杀活动', roles: ['ROLE_ADMIN', 'ROLE_MERCHANT'] }
      }
    ]
  },
  // 用户管理
  {
    path: '/user',
    component: () => import('../layout/index.vue'),
    redirect: '/user/list',
    meta: { title: '用户管理', icon: 'User', roles: ['ROLE_ADMIN'] },
    children: [
      {
        path: 'list',
        name: 'UserList',
        component: () => import('../views/user/list.vue'),
        meta: { title: '用户列表', roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'detail/:id',
        name: 'UserDetail',
        component: () => import('../views/user/detail.vue'),
        meta: { title: '用户详情', roles: ['ROLE_ADMIN'], activeMenu: '/user/list' },
        hidden: true
      }
    ]
  },
  // 配送管理
  {
    path: '/delivery',
    component: () => import('../layout/index.vue'),
    redirect: '/delivery/task',
    meta: { title: '配送管理', icon: 'Van', roles: ['ROLE_ADMIN', 'ROLE_DELIVERY'] },
    children: [
      {
        path: 'task',
        name: 'DeliveryTask',
        component: () => import('../views/delivery/task.vue'),
        meta: { title: '配送任务', roles: ['ROLE_ADMIN', 'ROLE_DELIVERY'] }
      },
      {
        path: 'map',
        name: 'DeliveryMap',
        component: () => import('../views/delivery/map.vue'),
        meta: { title: '配送地图', roles: ['ROLE_ADMIN', 'ROLE_DELIVERY'] }
      }
    ]
  },
  // 系统设置
  {
    path: '/setting',
    component: () => import('../layout/index.vue'),
    redirect: '/setting/system',
    meta: { title: '系统设置', icon: 'Setting', roles: ['ROLE_ADMIN'] },
    children: [
      {
        path: 'system',
        name: 'SystemSetting',
        component: () => import('../views/setting/system.vue'),
        meta: { title: '系统配置', roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'permission',
        name: 'PermissionSetting',
        component: () => import('../views/setting/permission.vue'),
        meta: { title: '权限管理', roles: ['ROLE_ADMIN'] }
      }
    ]
  },
  // 404页面
  {
    path: '/404',
    component: () => import('../views/error/404.vue'),
    meta: { hidden: true }
  },
  // 捕获所有未匹配路由
  { 
    path: '/:pathMatch(.*)*', 
    redirect: '/404', 
    meta: { hidden: true } 
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - Easy Mall管理系统` : 'Easy Mall管理系统'
  
  // 获取token
  const token = localStorage.getItem('token')
  
  // 如果访问登录页且已有token，直接跳转到首页
  if (to.path === '/login' && token) {
    next({ path: '/' })
    return
  }
  
  // 如果没有token且不是登录页，跳转到登录页
  if (!token && to.path !== '/login') {
    next({ path: '/login' })
    return
  }
  
  // 如果有token，检查权限
  if (token && to.path !== '/login') {
    // 获取用户角色
    const userRolesStr = localStorage.getItem('userRoles')
    const userRoles = userRolesStr ? JSON.parse(userRolesStr) : []
    
    // 检查路由是否需要权限
    if (to.meta.roles && to.meta.roles.length > 0) {
      // 检查用户是否有权限访问该路由
      const hasPermission = userRoles.some((role: string) => {
        return (to.meta.roles as string[]).includes(role)
      })
      
      if (hasPermission) {
        next()
      } else {
        ElMessage.error('没有权限访问该页面')
        next({ path: '/dashboard' })
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router